import json
import datetime

from applications.extensions import db
from applications.models import BorrowInfo, BookInfo, LicenceInfo
from flask import Blueprint, request, jsonify
from applications.models.statusMsg import responseMessage

borrowInfo_bp = Blueprint('borrowInfo', __name__, url_prefix='/borrowInfo')

@borrowInfo_bp.post('/borrow')
def borrowBook():
    try:
        if request.method == 'POST':
            borrow_info = request.form
            user_phone = borrow_info['user_phone']
            licence = LicenceInfo.query.filter_by(phonenum=user_phone).first()
            if not licence:
                return jsonify({'message': 'invalid licence'})
            elif licence.ispunish:
                return jsonify({'message': 'nolicence'})
            elif licence.status != "正常":
                return jsonify({'message':'licence status'})
            else:
                # 在数据库中更新借阅信息
                book = BookInfo.query.filter_by(isbn=borrow_info.get("borrow_isbn")).first()
                if not book:
                    return jsonify({'message': 'book not found'})
                if book.borrow_status == 1:
                    return jsonify({'message': 'book has been borrowed'})

                # 更新书籍的borrow_status
                book.borrow_status = 1
                borrow_time = datetime.datetime.now()  # 借出时间
                should_return_time = borrow_time + datetime.timedelta(days=60)
                # 在数据库中插入借阅信息
                borrow = BorrowInfo(
                    book_id=borrow_info['id'],
                    book_name=borrow_info['book_name'],
                    isbn=borrow_info['borrow_isbn'],
                    user_phonenum=borrow_info['user_phone'],
                    should_return_time = should_return_time
                )
                db.session.add(borrow)
                db.session.commit()

                # 返回成功响应
                return jsonify({'message': 'success'})
    except BaseException as e:
        print(e)
        return json.dumps(responseMessage(status="200", responsemsg="error").__dict__, ensure_ascii=False)
@borrowInfo_bp.get('/getAllBorrowInfo')
def getAllBorrowInfo():
    try:
        data = request.args
        user_phonenum = data.get("user_phonenum")
        borrow_info = BorrowInfo.query.filter_by(user_phonenum=user_phonenum).all()
        borrow_list = []
        for info in borrow_info:
            borrow_dict = {}
            borrow_dict['book_id'] = info.book_id
            borrow_dict['book_name'] = info.book_name
            borrow_dict['isbn'] = info.isbn
            borrow_dict['borrow_time'] = info.borrow_time.strftime('%Y-%m-%d %H:%M:%S')
            borrow_dict['should_return_time'] = info.should_return_time.strftime('%Y-%m-%d %H:%M:%S')
            borrow_dict['userborrow_status'] = info.status
            borrow_list.append(borrow_dict)
        return jsonify(borrow_list)
    except BaseException as e:
        print(e)
        return jsonify({'message': 'fail'})
@borrowInfo_bp.post('/return')
def returnBook():
    try:
        if request.method == 'POST':
            return_info = request.form
            borrow = BorrowInfo.query.filter_by(isbn=return_info.get("return_isbn"), user_phonenum=return_info['user_phonenum'],status=0).first()
            if borrow is None:
            # 如果没有匹配的借阅信息，返回错误响应
                return jsonify({'message': 'failed', 'reason': 'No matching borrowing record'})
            else:
            # 将借阅状态更新为已归还
                borrow.status = 1

            # 在 bookInfo 表中将 borrow_status 更新为未借出
            book = BookInfo.query.filter_by(isbn=return_info.get("return_isbn")).first()
            if book is not None:
                book.borrow_status = 0

            db.session.commit()
            # 判断是否违约
            should_return_time = borrow.should_return_time
            if datetime.now() > should_return_time:
                licence = LicenceInfo.query.filter_by(phonenum=return_info['user_phonenum']).first()
                licence.suspended_timeout = datetime.now() + datetime.timedelta(days=3)
            db.session.commit()
            # 返回成功响应
            return jsonify({'message': 'success'})

    except BaseException:
        return json.dumps(responseMessage(status="200", responsemsg="error").__dict__, ensure_ascii=False)